package com.tanguy.user.ui.trip.activity

import android.app.Activity
import android.content.Intent
import android.support.annotation.LayoutRes
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PagerSnapHelper
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewStub
import cn.sinata.xldutils_kotlin.utils.SpanBuilder
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.bean.orde.BaseOrderBean
import com.tanguy.user.bean.orde.StationOrderBean
import com.tanguy.user.bean.station.CarBean
import com.tanguy.user.bean.station.DockingBean
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.ui.trip.activity.adapter.CarTypeAdapter
import com.tanguy.user.ui.trip.activity.choice.HelpOtherCallActivity
import com.tanguy.user.ui.trip.activity.work.WaitDriverActivity
import com.tanguy.user.ui.window.SelectDateWindow
import com.tanguy.user.utlis.TimeUtils
import com.tanguy.user.utlis.extend.*
import com.tanguy.user.utlis.pay.PayWindow
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivityForResult
import java.util.*

/**
 * Created by dab on 2017/10/24 0024 17:32
 * 接送机，接送站，的父类，这里主要处理逻辑和通用的布局，那四个子类主要处理特殊界面相关的显示等等
 */
abstract class BasePickerActivity : ImmersionTitleActivity() {
    var dockingBean: DockingBean? = null
    override fun setContentViewRes(): Int = R.layout.activity_base_picker
    abstract val type: Int//1=接机 2=送机 3=接站 4=送站
    //准备下单的订单信息
    private val baseOrderBean by lazy { getOrderBean() }

    private var aMapLocationClient: AMapLocationClient? = null
    private val data = ArrayList<CarBean>()
    val carTypeAdapter = CarTypeAdapter(data)
    var carTypePosition = -1

    var cityCode: String? = null
    var cityName: String? = null
    override fun initView() {
        super.initView()
        title = getStringByType()
        val butText = "确认" + getStringByType()
        setText(R.id.btn_next, butText)
        setText(R.id.btn_next_no_price, butText)
        initCarType(find(R.id.rv_car_type))
        find<ViewStub>(R.id.vs_stub).apply {
            layoutResource = getSpecialViewRes()
            inflate()
        }

    }

    override fun initEvent() {
        super.initEvent()
        hindPriceLayout(true)
        //这个确认按钮只是确认价格,无法呼叫,呼叫用下面的发单
        click(R.id.btn_next_no_price) {
            if (baseOrderBean is StationOrderBean) {
                calculatingPrice(baseOrderBean as StationOrderBean)
            }
        }
        click(R.id.ttlv_switch_user) {
            loginGuarantee {
                if (it == null) return@loginGuarantee
                //替他人叫车
                startActivityForResult<HelpOtherCallActivity>(Const.RequestCode.SELECT_USER)
            }
        }
        click(R.id.tv_time) {
            showPopupWindow(SelectDateWindow(this@BasePickerActivity) { timestamp, timeString, errMsg ->
                if (errMsg != null) {
                    showToast(errMsg)
                } else {
                    loge("正确时间" + timestamp)
                    baseOrderBean.bybustime = timestamp.toTimeString(TimeUtils.TIME_YYYY_MM_DD_HH_MM_SS)
                    setText(R.id.tv_time, timeString)
                }
            })
        }
        //发单
        click(R.id.btn_next) {
            loginGuarantee {
                if (it == null) return@loginGuarantee
                if (type == 3 && baseOrderBean is StationOrderBean) {
                    HttpManager.dockOrder(baseOrderBean as StationOrderBean)
                            .requestSucceed(this) {
                                val orderId = it.get("orderId").asString
                                loge(orderId)
                                pay(orderId)
                            }
                }
                if (type == 4 && baseOrderBean is StationOrderBean) {
                    HttpManager.galconOrder(baseOrderBean as StationOrderBean)
                            .requestSucceed(this) {
                                val orderId = it.get("orderId").asString
                                loge(orderId)
                                pay(orderId)
                            }
                }

            }

        }


    }

    private fun pay(orderId: String) {
//        code:0成功1失败2取消3.确认中
        showPopupWindow(PayWindow(this, baseOrderBean.payMoney, orderId) { code, type ->
            when (code) {
                1 -> showToast("支付失败了")
                2 -> showToast("取消支付了")
                3 -> showToast("支付确认中，请稍后在订单中确认")
                0 -> startActivityForResult<WaitDriverActivity>(Const.RequestCode.WAIT_DRIVER, "orderId" to orderId, "type" to type)
            }
        })
    }

    override fun initData() {
        super.initData()
        location()
    }

    fun location() {
        rxPermissionsLocation {
            showDialog()
            location {
                this.aMapLocationClient = aMapLocationClient
                dismissDialog()
                if (it == null) {
                    showToast("定位失败")
                    return@location
                }
                onLocationSucceed(it)
                cityCode = it.cityCode
                cityName = it.city
                docking(it.cityCode, it.city)
            }
        }
    }

    open fun onLocationSucceed(aMapLocation: AMapLocation) {}

    //进来就调的(定位成功以后)
    private fun docking(cityCode: String, cityName: String) {
        HttpManager.docking(type, cityCode)
                .requestSucceed(this) {
                    dockingBean = it
                    carTypeAdapter.setNewData(it.car)
                }
    }

    /**
     * 初始化ViewStub的，因为这个是每个子类特殊的布局
     */
    @LayoutRes
    abstract fun getSpecialViewRes(): Int

    /**
     * 获取公共的订单信息
     */
    abstract fun getOrderBean(): BaseOrderBean

    /**
     * 当选择车型改变的时候
     */
    abstract fun onCarTypeChanged(position: Int)


    private val linearLayoutManager by lazy {
        LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
    }

    /**
     * 初始化车辆类型
     */
    private fun initCarType(rvCarType: RecyclerView) {
        rvCarType.layoutManager = linearLayoutManager
        rvCarType.adapter = carTypeAdapter
        PagerSnapHelper().attachToRecyclerView(rvCarType)
        rvCarType.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState != RecyclerView.SCROLL_STATE_IDLE) return
                val carType = getCarType()
                if (carTypePosition != carType)
                    onCarTypeChanged(carType)
            }

        })
    }

    private fun getCarType(): Int {
        val position = linearLayoutManager.findFirstCompletelyVisibleItemPosition()
        return if (position in 0 until data.size) position else -1
    }

    /**
     * 显示隐藏价格的显示
     */
    private fun hindPriceLayout(hind: Boolean) {
        find<View>(R.id.btn_next_no_price).visibility = if (hind) View.VISIBLE else View.GONE
        find<View>(R.id.layout_show_price).visibility = if (hind) View.GONE else View.VISIBLE
    }

    private fun getStringByType(): String {
        when (type) {
            1 -> return "接机"
            2 -> return "送机"
            3 -> return "接站"
        }
        return "送站"
    }

    /**
     * 计算价格
     */
    open fun calculatingPrice(cockOrderBean: StationOrderBean) {
        if (cockOrderBean.siteId.isNullOrEmpty()) {
            showToast("请先选择站点")
            return
        }
        if (cockOrderBean.boulat.isNullOrEmpty() || cockOrderBean.boulon.isNullOrEmpty()) {
            showToast("请选择终点")
            return
        }
        carTypePosition = getCarType()
        if (carTypePosition < 0) {
            cockOrderBean.gradeId = "0"
        } else {
            cockOrderBean.gradeId = data[carTypePosition].id.toString()
        }
        loginGuarantee {
            if (it == null) return@loginGuarantee
            cockOrderBean.userId = it.userId.toString()
            HttpManager.calculate(cockOrderBean)
                    .requestSucceed(this) {
                        loge(it.toString())
                        //todo 这里get 拿到的可能为null,需要特殊处理下
                        val sf = it.get("sf").asDouble
                        val money = it.get("money").asDouble
                        val couId = it.get("couId").asInt
                        val context = it.get("context").asString
                        hindPriceLayout(false)
                        val totalMoney = String.format(Locale.CHINA, getStringByType() + "费用%.2f元", sf - money)
                        val stringBuilder = SpanBuilder(totalMoney).size(4, totalMoney.length - 1, 20)
                                .color(this, 4, totalMoney.length - 1, R.color.color_fb408e)
                                .build()
                        setText(R.id.tv_total_money, stringBuilder)
                        val priceString = String.format(Locale.CHINA, context + ",折扣卷抵扣%.2f元", money)
                        setText(R.id.tv_hint_price, priceString)
                        cockOrderBean.coupId = couId.toString()
                        cockOrderBean.totalmoney = sf.toString()
                        cockOrderBean.offstmoney = money.toString()
                        cockOrderBean.payMoney = sf - money
                    }
            loge(cockOrderBean.toString())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        aMapLocationClient?.stopLocation()
        aMapLocationClient?.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Const.RequestCode.SELECT_USER && data != null) {
                val name = data.getStringExtra("name")
                val me = data.getBooleanExtra("me", false)
                val phone = data.getStringExtra("phone")
                if (me) {
                    setTextLeft(R.id.ttlv_switch_user, "自己乘车")
                    baseOrderBean.ista = "2"
                    baseOrderBean.taname = ""
                    baseOrderBean.taphone = ""
                } else {
                    setTextLeft(R.id.ttlv_switch_user, "$name ($phone)")
                    baseOrderBean.ista = "1"
                    baseOrderBean.taname = name
                    baseOrderBean.taphone = phone
                }
            }
            //司机已经接单了
            if (requestCode == Const.RequestCode.WAIT_DRIVER) {
                finish()
            }
        }
    }
}